package com.ms.base.web.mvc;

import com.ms.base.comm.cloud.ResultDto;
import com.ms.base.comm.util.FrameUtil;
import com.ms.base.page.core.PageParamModel;
import com.ms.base.page.core.PageUtil;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <b>description</b>：web工具 <br>
 * <b>time</b>：2018-08-14 13:29 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class WebUtil {
    public static final String REQUEST_RESULT = "REQUEST_RESULT";
    //url路径分隔符
    public static final String URL_SPLIT = "/";


    /**
     * 获取完整的url
     *
     * @param url      url
     * @param paramMap 参数
     * @return
     */
    public static String getUrl(String url, Map<String, Object> paramMap) {
        StringBuilder s = new StringBuilder(url);
        s.append(mapToRequestParam(paramMap));
        return s.toString();
    }

    /**
     * 获取完整的url
     *
     * @param path 相对路径
     * @return
     */
    public static String getPathUrl(String path) {
        if (path == null) {
            return null;
        }
        return getPathUrl(path, null);
    }

    /**
     * 获取完整的url
     *
     * @param path     相对路径
     * @param paramMap
     * @return
     */
    public static String getPathUrl(String path, Map<String, Object> paramMap) {
        StringBuilder s = new StringBuilder();
        s.append(getRootUrl()).append(path).append(mapToRequestParam(paramMap));
        return s.toString();
    }

    /**
     * 获取根路径
     *
     * @return
     */
    public static String getRootUrl() {
        return WebConfigProperties.webConfigProperties().getSitefilter().rootUrl();
    }

    /**
     * map转换为请求参数
     *
     * @param paramMap map对象
     * @return
     */
    public static String mapToRequestParam(Map<String, Object> paramMap) {
        return FrameUtil.mapToRequestParam(paramMap, false);
    }


    /**
     * 获取request中的参数
     *
     * @param request 请求对象
     * @param name    参数名称
     * @return
     */
    public static String getParameter(HttpServletRequest request, String name) {
        return request.getParameter(name);
    }

    /**
     * 获取request中的参数
     *
     * @param request 请求对象
     * @param name    参数名称
     * @return
     */
    public static String[] getParameterValues(HttpServletRequest request, String name) {
        return request.getParameterValues(name);
    }

    /**
     * 获取request中的请求参数
     *
     * @return
     */
    public static Map<String, Object> getParameterMap(HttpServletRequest request) {
        return getParameterMap(request, false);
    }

    /**
     * 获取request中的请求参数
     *
     * @param request 请求对象
     * @param more    是否获取一个name对应多个值
     * @return
     */
    public static Map<String, Object> getParameterMap(HttpServletRequest request, boolean more) {
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        Map<String, String[]> paramMap = request.getParameterMap();
        for (String name : paramMap.keySet()) {
            Object value = null;
            String[] values = paramMap.get(name);
            if (more) {
                value = values;
            } else {
                if (values != null && values.length >= 1) {
                    value = values[0];
                }
            }
            parameterMap.put(name, value);
        }
        return parameterMap;
    }

    /**
     * 将结果放入request
     *
     * @param request
     * @param resultDto
     */
    public static void putResultDto(HttpServletRequest request, ResultDto resultDto) {
        request.setAttribute(REQUEST_RESULT, resultDto);
    }

    /**
     * 获取某个controller某个方法的返回的viewname<br/>
     * 如：getControllerViewName("system","index","m1") = system/index/m1
     *
     * @param moduleName
     * @param controllerName
     * @param method
     * @return
     */
    public static String getControllerViewName(String moduleName, String controllerName, String method) {
        StringBuilder result = new StringBuilder();
        if (StringUtils.isNotBlank(moduleName)) {
            result.append(moduleName);
        }
        if (StringUtils.isNotBlank(controllerName)) {
            result.append("/").append(controllerName);
        }
        if (StringUtils.isNotBlank(method)) {
            result.append("/").append(method);
        }
        return result.toString();
    }

    /**
     * 获取controller某个方法请求的完整路径 <br/>
     * 如：getControllerUrl("system","index","m1") = http://admin.ms.org/system/index/m1
     *
     * @param moduleName     模块名称
     * @param controllerName controller名称
     * @param method         方法名称
     * @return
     */
    public static String getControllerUrl(String moduleName, String controllerName, String method) {
        return getControllerUrl(moduleName, controllerName, method, null);
    }

    /**
     * 获取controller某个方法请求的完整路径 <br/>
     * 如：getControllerUrl("system","index","m1",{"a":"1","b","2"}) = http://admin.ms.org/system/index/m1?a=1&b=2
     *
     * @param moduleName     模块名称
     * @param controllerName controller名称
     * @param method         方法名称
     * @param paramMap       ?之后的参数
     * @return
     */
    public static String getControllerUrl(String moduleName, String controllerName, String method, Map<String, Object> paramMap) {
        return getPathUrl(getControllerPath(moduleName, controllerName, method), paramMap);
    }

    /**
     * 获取controller某个方法对应的path<br/>
     * 如：getControllerPath("system","index","m1") = /system/index/m1
     *
     * @param moduleName     模块名称
     * @param controllerName controller名称
     * @param method         方法名称
     * @return
     */
    public static String getControllerPath(String moduleName, String controllerName, String method) {
        StringBuilder result = new StringBuilder();
        if (StringUtils.isNotBlank(moduleName)) {
            result.append("/").append(moduleName);
        }
        if (StringUtils.isNotBlank(controllerName)) {
            result.append("/").append(controllerName);
        }
        if (StringUtils.isNotBlank(method)) {
            result.append("/").append(method);
        }
        return result.toString();
    }

    /**
     * 获取controller的名称
     *
     * @param controller
     * @return
     */
    public static String getControllerName(Class controller) {
        String simpleName = controller.getSimpleName();
        return simpleName.substring(0).toLowerCase() + simpleName.substring(1, simpleName.indexOf("Controller"));
    }

    /**
     * 获取分页参数
     *
     * @param request
     * @return
     */
    public static PageParamModel getPageParamModel(HttpServletRequest request) {
        return PageUtil.buildPageParamModel(getParameterMap(request));
    }

    /**
     * 返回用户的IP地址
     *
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String ip = getIpAddr(request);
        if (StringUtils.isNotBlank(ip) && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    private static String getIpAddr(HttpServletRequest request) {
        // 微信站要通过这个参数来传递用户的ip地址
        String ip = request.getParameter("regip");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        } else {
            return disposeIp(ip);
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("wl-proxy-client-ip");
        } else {
            return disposeIp(ip);
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            if (StringUtils.isNotBlank(ip)) {
                ip = ip.split(",")[0];
            }
        } else {
            return disposeIp(ip);
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("REMOTE_ADDR");
        } else {
            return disposeIp(ip);
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        } else {
            return disposeIp(ip);
        }

        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        } else {
            return disposeIp(ip);
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        } else {
            return disposeIp(ip);
        }
        return disposeIp(ip);
    }

    private static String disposeIp(String ip) {
        if (StringUtils.isBlank(ip)) {
            return ip;
        }
        if (ip.indexOf(",") != -1) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }

    /**
     * 是否是绝对路径
     *
     * @param url 验证url是否是绝对路径
     * @return
     */
    public static boolean isAbsoluteUrl(String url) {
        return StringUtils.isNotBlank(url) && (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https"));
    }

    /**
     * 获取请求的uri不包含contextpath
     *
     * @param request
     * @return
     */
    public static String getRequestUri(HttpServletRequest request) {
        String contextpath = request.getContextPath();
        String uri = request.getRequestURI();
        if (StringUtils.isNotBlank(contextpath) && uri.startsWith(contextpath)) {
            return uri.substring(contextpath.length());
        }
        return uri;
    }

}
